package com.ll.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 *
 * 类名: StringUtil <br/>
 * 功能: <br/>
 * 日期: 2016年1月7日 下午1:50:18 <br/>
 *
 * @author ronglian
 */
public class StringUtil {
	
	private static final String TOTAL_STRING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

	private static final String TOTAL_COUPON_STRING = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";

	private static final Logger LOGGER = LoggerFactory.getLogger(StringUtil.class);
	
	/**
	 * 生成随机数
	 * 
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length) {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; ++i) {
			int number = random.nextInt(TOTAL_STRING.length());// [0,62)
			sb.append(TOTAL_STRING.charAt(number));
		}
		return sb.toString();
	}

	public static final String genCouponCode(int length){
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; ++i) {
			int number = random.nextInt(TOTAL_COUPON_STRING.length());// [0,62)
			sb.append(TOTAL_COUPON_STRING.charAt(number));
		}
		return sb.toString();
	}
	
	/**
	 * 生成MD5
	 * 
	 * @param pwd
	 * @param saltfigure
	 * @return
	 */
	public static String calMD5(String pwd, String saltfigure) {
		String saltPassword = pwd + saltfigure;
		String md5 = DigestUtils.md5Hex(saltPassword);
		return md5;
	}

	/**
	 * 生成订单号，时间戳精确到ms +六位随机数
	 * 
	 * @return
	 */
	public static String genOrderSn() {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		sb.append(System.currentTimeMillis());
		for (int i = 0; i < 6; ++i) {
			sb.append(random.nextInt(10));
		}
		return sb.toString();
	}

	/**
	 * 返回正确的url链接
	 * 
	 * @param url
	 * @return
	 */
	public static String urlChecking(String url) {
		Integer hLinkType = null;
		String hLink = "";
		if (url.indexOf("ttp:/") > 0) {
			hLinkType = 0;
			url = url.replaceAll("http://", "");
		}
		if (url.indexOf("ttps:/") > 0) {
			hLinkType = 1;
			url = url.replaceAll("https://", "");
		}
		if (hLinkType != null) {
			url = hLinkType == 0 ? "http://" + url : "https://" + url;
		}
		return url;
	}

	/**
	 * 
	 * 功能: 字符串补全<br/>
	 * 说明: 如1补全成0001<br/>
	 * 
	 * @author yubin
	 * @param c
	 *            填充字符
	 * @param len
	 *            补全完成后字符串长度
	 * @param str
	 *            原始字符串
	 * @param cpltType
	 *            补全类型
	 * @return
	 * @return String
	 *
	 */
	public static String complementStr(String str, char c, int len, ComplementType cpltType) {
		int strLen = str.length();
		// 如果补全后的长度不大于原始字符串长度，则不作处理
		if (len <= strLen) {
			return str;
		}
		StringBuilder sb = new StringBuilder();
		char[] charArr = new char[len - strLen];
		for (int i = 0; i < charArr.length; i++) {
			charArr[i] = c;
		}
		if (cpltType.getValue() == 0) {
			sb.append(charArr);
			sb.append(str);
		} else {
			sb.append(str);
			sb.append(charArr);
		}
		return sb.toString();
	}
	

	
	/**
	 * 
	 * 功能: 通用码生成<br/>
	 * 说明: 生成码格式 = preFix + concatStr + codeCount位随机数字<br/>
	 * <br/>
	 * 
	 * @author yubin
	 * @param prefix
	 *            前缀
	 * @param codeCount
	 *            码内容位数
	 * @param concatStr
	 *            连接符
	 * 
	 * @return String 生成码，示例：UEC-732984
	 *
	 */
	public static final String genCommonCode(String prefix, int codeCount, String concatStr) {
		StringBuilder sb = new StringBuilder(prefix);
		if (concatStr != null && concatStr.length() > 0) {
			sb.append(concatStr);
		}
		sb.append(RandomStringUtils.randomNumeric(codeCount));
		return sb.toString();
	}

	/**
	 * 判断是否为整数
	 *
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}

	/**
	 * 判断是否为浮点数（含整数）
	 *
	 * @param str
	 * @return
	 */
	public static boolean isFloatNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]+\\.*[0-9]*");
		return pattern.matcher(str).matches();
	}

	/**
	 * 判断是否为yyyyMMdd的日期格式
	 *
	 * @param date
	 * @return
	 */
	public static boolean isDateyyyyMMdd(String date) {
		String regex = "[0-9]{4}-[0-9]{2}-[0-9]{2}";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(date);
		if (matcher.matches()) {
			return true;
		}
		return false;
	}

	/**
	 * 创建UUID字符串，并将中间的分割线去掉
	 * @return 没有中间分割线的uuid
	 */
	public static final String createUUID(){
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	/**
	 * 将字符串数组拆分成二维数组
	 * @param arr 原字符串数组
	 * @param n 二维数组中，每个数组元素中的个数
	 * @return 拆分完成后的一个二维数组
	 */
	public static final String[][] split4Array(String[] arr,int n){
		if(arr == null)
			return new String[][]{{}};
		if(n <= 0){
			throw new IllegalArgumentException("n can not less than zero or equal zero!!");
		}
		int total = arr.length;
		int m = total / n ;
		if((total % n) != 0){
			m ++;
		}
		String[][] result = new String[m][n];;
		for(int i=0;i<result.length;i++){
			for(int j=0;j<result[i].length;j++){
				int pointer = i*n+j;
				if(pointer < total){
					result[i][j] = arr[pointer];
				}
			}
		}
		return result;
	}
	/**
	 * 将字符串数组拆分成二维数组,默认每个数组中有100个元素
	 * @param arr 原字符串数组
	 * @return 拆分完成后的一个二维数组
	 */
	public static final String[][] split4Array(String[] arr){
		return split4Array(arr,100);
	}


	public static final List<List<String>> split4List(List<String> list, int n){
		String[] arr = list.toArray(new String[]{});
		String[][] tmp = split4Array(arr,n);
		List<List<String>> result = new ArrayList<List<String>>();
		for(String[] item:tmp){
			result.add(Arrays.asList(item));
		}
		return result;
	}

	public static final List<List<String>> split4List(List<String> list){
		return split4List(list,100);
	}



	public static enum ComplementType {
		/**
		 * 补全类型0_前补
		 */
		BEFORE(0),
		/**
		 * 补全类型1_后补
		 */
		AFTER(1);

		private final Integer value;

		private ComplementType(Integer value) {
			this.value = value;
		}

		/**
		 * @return the value
		 */
		public Integer getValue() {
			return value;
		}

		public String getValueStr() {
			return String.valueOf(value);
		}
	}


}
